<template>
  <el-main>
    <!-- 查询条件 -->
    <el-form :model="searchModel" ref="searchForm" label-width="80px" :inline="true" size="small"
             style="margin-left: 40px">
      <el-form-item>
        <el-input v-model="searchModel.name" placeholder="请输入楼层，如（一楼）"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="search(pageNo,pageSize)">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetValue()">重置</el-button>
        <el-button type="success" icon="el-icon-plus" size="small" @click="openAddWindow()"
                   v-if="hasPermission('sys:provider:add')">新增
        </el-button>
      </el-form-item>
    </el-form>
    <!--  数据表格-->
    <div class="home-card">
      <el-card class="box-card" v-for="item in providerList" :key="item.id">
        <div slot="header" class="clearfix">
          <span>{{ item.name }}</span>
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(item)"
                     v-if="hasPermission('sys:provider:edit')" style="float: right;padding: 5px 5px"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(item)"
                     v-if="hasPermission('sys:provider:delete')" style="float: right;padding: 5px 5px"></el-button>
        </div>
        <div class="text item">
          <el-image style="width: 250px; height: 250px" :src="item.icon" fit="fill"
                    :preview-src-list="[item.icon]"></el-image>
        </div>
        <p></p>
        <div style="height: 30px">{{ item.nameDesc }}</div>
        <div style="text-align: right">
<!--          <el-tag style="margin-right: 5px">￥{{ item.price }}</el-tag>-->
            <el-tag v-if="item.price===0" size="normal">空闲</el-tag>
            <el-tag type="info" v-else-if="item.price===1" size="normal">已预约</el-tag>
          <el-button v-if="item.price===0" type="success" icon="el-icon-s-goods" size="mini" @click="handleAdd(item)">预约</el-button>
        </div>
      </el-card>
    </div>
    <!--    分页工具-->
    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                   :current-page="pageNo" :page-sizes="[10,20,30,40,50]" :page-size="10"
                   layout="total,sizes,prev,pager,next,jumper" :total="total">
    </el-pagination>
    <!--    新增和修改对话框-->
    <system-dialog :title="providerDialog.title" :visible="providerDialog.visible" :width="providerDialog.width"
                   :height="providerDialog.height" @onClose="onClose()"
                   @onConfirm="onConfirm()">
      <template slot="content">
        <el-form :model="provider" ref="providerForm" label-width="80px" size="small" :rules="rules">
          <el-form-item label="楼层" prop="name">
            <el-input v-model="provider.name" placeholder="请输入楼层名称"></el-input>
          </el-form-item>
          <el-form-item label="座位状态" prop="price">
            <el-input v-model="provider.price" placeholder="请输入座位状态（0表示空闲，1表示已预约）"></el-input>
          </el-form-item>
          <el-form-item label="商品图片" prop="icon">
            <el-input v-model="provider.icon" placeholder="请输入自习室座位图片地址" width="500"></el-input>
          </el-form-item>
          <el-form-item label="商品描述">
            <el-input type="textarea" v-model="provider.nameDesc" placeholder="请输入详细座位号"></el-input>
          </el-form-item>
        </el-form>
      </template>
    </system-dialog>
    <!--    下单对话框-->
    <system-dialog :title="orderDialog.title" :visible="orderDialog.visible" :width="orderDialog.width"
                   :height="orderDialog.height" @onClose="onOrderClose()"
                   @onConfirm="onOrderConfirm()">
      <div slot="content">
        <el-form :model="order" ref="orderForm" label-width="80px" size="small" :inline="true" :rules="orderRules">
          <el-image style="width: 375px; height: 305px" :src="order.providerIcon" fit="fill"
                    :preview-src-list="[order.providerIcon]"></el-image>
          <p></p>
<!--          <el-form-item label="收货地址" prop="selectedOptions">-->
<!--            <el-cascader size="small" :options="pcaTextArr" v-model="selectedOptions"-->
<!--                         style="width: 290px"></el-cascader>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="详细地址" prop="userAddress">-->
<!--            <el-input type="textarea" v-model="order.userAddress" placeholder="请输入详细地址"-->
<!--                      style="width: 290px"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="预约人" prop="userName">
            <el-input v-model="order.userName" placeholder="请输入预约人姓名" style="width: 290px"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="userPhone">
            <el-input v-model="order.userPhone" placeholder="请输入预约人手机号码" style="width: 290px"></el-input>
          </el-form-item>
<!--          <el-form-item label="采购数量">-->
<!--            <el-input-number v-model="order.orderCount" style="width: 100px"></el-input-number>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="共计￥">-->
<!--            <el-input disabled v-model="order.orderTotal" style="width: 100px"></el-input>-->
<!--          </el-form-item>-->
        </el-form>
      </div>
    </system-dialog>
  </el-main>
</template>

<script>
//导入对话框组件
import SystemDialog from "@/components/system/SystemDialog.vue";
//导入权限判断
import hasPermission from "@/permission/index";
//导入商品API
import providerApi from "@/api/provider"
//导入订单编号生成器
import createOrderNum from "@/utils/ordernum";
//导入省市区数据
import {pcaTextArr} from "element-china-area-data";
import orderApi from '@/api/order'

export default {
  name: "providerList",
  //注册组件
  components: {
    SystemDialog
  },
  data() {
    //自定义检验规则
    let validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号'));
      } else if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('手机号格式不正确'));
      } else {
        callback();
      }
    };
    return {
      pcaTextArr,
      selectedOptions: [],
      //查询条件
      searchModel: {
        name: "",//商品名称
        pageNo: 1,//当前页
        pageSize: 10,//每页显示条数
        userId: this.$store.getters.userId,//用户ID
      },
      providerList: [],//表格数据
      pageNo: 1,//当前页
      pageSize: 10,//每页显示条数
      total: 0,//总条数
      rules: {
        name: [{required: true, message: '请输入座位名称', trigger: 'blur'}],
        price: [{required: true, message: '请输入座位状态（0表示空闲）', trigger: 'blur'}],
        icon: [{required: true, message: '请输入商品图片地址', trigger: 'blur'}],
      },
      orderRules: {
        // userAddress: [{required: true, message: '请输入详细地址', trigger: 'blur'}],
        userName: [{required: true, message: '请输入预约人姓名', trigger: 'blur'}],
        userPhone: [{validatePhone: validatePhone, trigger: 'blur', required: true}]
      },
      providerId: "",//商品ID
      //添加和修改商品
      providerDialog: {
        title: "",//对话框标题
        visible: false,//对话框是否显示
        width: 400,//对话框宽度
        height: 250,//对话框高度
      },
      orderDialog: {
        title: "",//对话框标题
        visible: false,//对话框是否显示
        width: 400,//对话框宽度
        height: 430,//对话框高度
      },
      //商品对象
      provider: {
        id: '',//商品ID
        name: '',//商品名称
        price: '',//商品价格
        nameDesc: '',//商品描述
        icon: '',//商品图片地址
      },
      //订单对象
      order: {
        id: '',//订单ID
        providerId: '',//商品ID
        providerName: '',//商品名称
        providerPrice: 0,//商品价格
        providerIcon: '',//商品图片地址
        userId: this.$store.getters.userId,//用户ID
        userName: '',
        userPhone: '',//用户收货手机号
        userAddress: '',//用户收货地址
        orderNumber: '',//订单编号
        orderCount: 1,//商品数量
        orderTotal: 0,//订单总金额
        orderStatus: 0,//订单状态
      },
    }
  },
  created() {
    //查询商品列表
    this.search();
  },
  methods: {
    hasPermission,
    /**
     * 查询商品列表
     */
    async search(pageNo = 1, pageSize = 10) {
      this.searchModel.pageNo = pageNo;//当前页
      this.searchModel.pageSize = pageSize;//每页显示条数
      //发送查询请求
      let res = await providerApi.getProviderListApi(this.searchModel);
      // console.log(res)
      //判断是否成功
      if (res.success) {
        this.providerList = res.data.records;//表格数据
        this.total = res.data.total;//总条数
      }
    },
    /**
     * 改变每页显示条数触发
     * @param size
     */
    handleSizeChange(size) {
      this.pageSize = size;//每页显示条数
      this.search(this.pageNo, size);
    },
    /**
     * 改变页码触发
     * @param page
     */
    handleCurrentChange(page) {
      this.pageNo = page;//当前页
      this.search(page, this.pageSize);
    },
    /**
     * 打开修改窗口
     */
    handleEdit(row) {
      //数据回显
      this.$objCopy(row, this.provider);//数据拷贝,将数据拷贝到provider对象中
      this.providerDialog.title = "编辑商品";//设置对话框标题
      this.providerDialog.visible = true;//设置对话框是否显示
    },
    /**
     * 删除商品
     * @return {Promise<void>}
     */
    async handleDelete(row) {
      let confirm = await this.$myconfirm("确定删除该商品吗？");
      if (confirm) {
        //封装条件
        let params = {id: row.id}
        //发送删除请求
        let res = await providerApi.deleteProviderApi(params);
        //判断是否成功
        if (res.success) {
          this.$message.success(res.message)//提示成功
          await this.search(this.pageNo, this.pageSize);//查询数据
        } else {
          this.$message.error(res.message)//提示失败
        }
      }
    },
    /**
     * 下单
     * @param row
     * @return {Promise<void>}
     */
    async handleAdd(row) {
      this.orderDialog.title = "商品下单";//设置对话框标题
      this.orderDialog.visible = true;//设置对话框是否显示
      //数据回显
      this.order.providerName = row.name;
      this.order.providerIcon = row.icon;
      this.order.providerPrice = row.price;
      this.order.providerId = row.id;
      this.order.orderTotal = row.price * this.order.orderCount;
      this.order.orderNumber = createOrderNum();
    },
    /**
     * 打开新增窗口
     */
    openAddWindow() {
      this.$resetForm("providerForm", this.provider);//清空表单数据
      this.providerDialog.title = "新增商品";//设置对话框标题
      this.providerDialog.visible = true;//设置对话框是否显示
    },
    /**
     * 关闭对话框
     */
    onClose() {
      //关闭窗口
      this.providerDialog.visible = false;
    },
    /**
     * 关闭对话框
     */
    onOrderClose() {
      //关闭窗口
      this.orderDialog.visible = false;
    },
    /**
     * 确认对话框
     */
    onConfirm() {
      //表单验证
      this.$refs.providerForm.validate(async valid => {
        if (valid) {
          let res = null;
          //判断用户ID是否有数据，如果用户ID为空，则表示新增，否则就是修改
          console.log(this.provider.id)
          if (this.provider.id === '') {
            //新增
            //发送新增请求
            res = await providerApi.addProviderApi(this.provider)
          } else {
            //修改
            //发送修改请求
            res = await providerApi.updateProviderApi(this.provider)
          }
          //判断是否成功
          if (res.success) {
            this.$message.success('操作成功')//提示成功
            this.providerDialog.visible = false//关闭窗口
          } else {
            this.$message.error(res.message)//提示失败
          }
        }
      });
    },
    /**
     * 确认下单
     */
    onOrderConfirm() {
      //验证表单
      this.$refs.orderForm.validate(async valid => {
        if (valid) {
          this.order.orderTotal = this.order.providerPrice * this.order.orderCount
          this.order.userAddress = this.selectedOptions + ',' + this.order.userAddress
          let res = await orderApi.addOrderApi(this.order)
          if (res.success) {
            this.$message.success(res.message)
            this.orderDialog.visible = false
            await this.search(this.pageNo, this.pageSize);//查询数据
          } else {
            this.$message.error(res.message)
          }
        }
      });
    },
    /**
     * 重置查询条件
     */
    resetValue() {
      //清空表单数据
      this.searchModel.name = "";
      //重新查询
      this.search();
    },
  },
}
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  margin: auto;
  display: flex;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 300px;
  margin-top: 10px;
  margin-left: 25px;
}

.home-card {
  width: 100%;
  overflow: hidden;
  padding: 10px 10px;
  display: flex;
  flex-wrap: wrap;
}
</style>
